package com.cskaoyan.realm;

import com.cskaoyan.bean.pojo.User;
import com.cskaoyan.bean.pojo.UserExample;
import com.cskaoyan.dao.UserMapper;
import com.cskaoyan.exception.UserLoginException;
import lombok.SneakyThrows;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: lds
 * @clsss: WxRealm
 */
@Configuration
public class WxRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;

    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        char[] password = token.getPassword();

        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        criteria.andPasswordEqualTo(new String(password));
        List<User> users = userMapper.selectByExample(userExample);

        System.out.println(users.size());
        String credential = users.size()>=1?users.get(0).getPassword():null;
        if (users.size() ==0){
            throw new UserLoginException(null,"用户名或密码错误");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(users.get(0), credential, this.getName());
        return authenticationInfo;


    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }


}
